#include "YLFW/YLFWWindow.h"
#include <YLFW/YLFWTexture.h>

static void CallBack(GLFWwindow* window, int width, int height) {
	glViewport(0, 0, width, height);
}

static bool hasInit = false;
YLFWWindow * YLFWWindow::CreateWindow(int width, int height, const char * title)
{
	if (!hasInit) {
		glfwInit();
		glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
		glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
		glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
	}

	GLFWwindow* window = glfwCreateWindow(width, height, title, NULL, NULL);
	if (window == NULL) {
		glfwTerminate();
		return NULL;
	}
	glfwMakeContextCurrent(window);

	if (!hasInit) {
		hasInit = true;
		if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress))
		{
			return NULL;
		}
	}
	glfwSetFramebufferSizeCallback(window, (GLFWframebuffersizefun)CallBack);

	YLFWWindow* ylfwWindow = new YLFWWindow(window);
	return ylfwWindow;
}

void YLFWWindow::Terminate()
{
	glfwTerminate();
}

void YLFWWindow::PullEvent()
{
	glfwPollEvents();
}

void YLFWWindow::Clear()
{
	glClearColor(0.5f, 0.5f, 0.5f, 1.0f);
	glClear(GL_COLOR_BUFFER_BIT);
}

YLFWWindow::YLFWWindow(GLFWwindow * window)
{
	this->window = window;
}

bool YLFWWindow::IsClose()
{
	return glfwWindowShouldClose(window);
}

void YLFWWindow::Close() {
	glfwSetWindowShouldClose(window,true);
}

bool YLFWWindow::GetKey(int key)
{
	return glfwGetKey(window,key);
}

void YLFWWindow::SwapBuffers()
{
	glfwSwapBuffers(window);
}

void YLFWWindow::DrawTriangles(Shader & shader, VertexObject &vObj,YLFWTexture& texture)
{
	glBindTexture(GL_TEXTURE_2D,texture.ID);
	glActiveTexture(GL_TEXTURE0);
	shader.use();
	shader.setInt("texture0", 0);
	vObj.DrawTriangles();
}

void YLFWWindow::DrawTriangles(Shader & shader, VertexObject &vObj, YLFWTexture& texture0, YLFWTexture& texture1)
{
	glActiveTexture(GL_TEXTURE0);
	glBindTexture(GL_TEXTURE_2D, texture0.ID);
	glActiveTexture(GL_TEXTURE1);
	glBindTexture(GL_TEXTURE_2D, texture1.ID);
	shader.use();
	shader.setInt("texture0", 0);
	shader.setInt("texture1", 1);
	vObj.DrawTriangles();
}
